<template>
    <div class="body">
        <div class="news-detail-page">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading">加载中...</div>
            <!-- 详情内容 -->
            <div v-else-if="newsData" class="detail-content">
                <h1 class="news-title">{{ newsData.newsTitle }}</h1>
                <div class="news-meta">
                    <img
                        src="https://p1.ssl.qhmsg.com/dr/270_500_/t0141eb943e203afa64.jpg"
                        alt="36K Logo"
                        class="news-logo"
                    >
                    <span class="publisher">{{ newsData.publisher }}</span>
                </div>

                <div class="news-content">
                    <!-- 将换行符转为<br>标签显示 -->
                    <p class="p-class" v-for="(paragraph, idx) in newsData.newsContent.split('\n')" :key="idx">
                        {{ paragraph }}
                    </p>
                </div>
            </div>
            <!-- 数据错误 -->
            <div v-else class="error">未找到新闻数据</div>
        </div>
    </div>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router'; // 用于获取路由参数
import request from '@/utils/request.js';

// 获取路由实例
const route = useRoute();

// 响应式数据
const newsData = ref(null);
const loading = ref(true);

// 页面加载时获取详情数据
onMounted(() => {
    // 从路由参数中获取新闻id
    const { id } = route.params;
    // 调用接口获取对应id的新闻（如果后端有详情接口）
    // 如果后端没有详情接口，也可以从列表数据中过滤（如下）
    request.get('/api/news/getNews').then(res => {
        if (res.code === 200) {
            // 从列表中筛选当前id对应的新闻
            newsData.value = res.data.find(item => item.id === Number(id));
        }
        loading.value = false;
    }).catch(err => {
        console.error('获取详情失败', err);
        loading.value = false;
    });
});
</script>

<style scoped>
/*设置一页背景*/


.news-detail-page {
    background-color: #F5F5DC;
    height: 900vh;
}
.detail-content {
    max-width: 800px;

    margin: 0 auto;
    padding: 200px;
}
.publisher{
    margin-left: 10px;
    color: #666;
    font-size: 1rem;
}
.news-title {
    font-size: 1.5rem;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
}

.news-meta {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    color: #666;
}
.news-logo {
    width: 30px;
    height: 30px;
    margin-right: 10px;
}
.news-content {
    line-height: 1.8;
    margin: 20px 0;
}
.news-content p {
    margin: 10px 0;
}
.p-class{
    text-indent: 2em;
    line-height: 1.8;
}
.loading, .error {
    text-align: center;
    padding: 50px;
    color: #666;
}
</style>